# MongoDB Sync for Windows PowerShell
Write-Host "🚀 MongoDB Sync for Windows" -ForegroundColor Green
Write-Host "==========================" -ForegroundColor Green

# 检查 Docker 是否运行
Write-Host "`n[INFO] Checking Docker..." -ForegroundColor Blue
try {
    docker version | Out-Null
    Write-Host "[SUCCESS] Docker is running" -ForegroundColor Green
} catch {
    Write-Host "[ERROR] Docker is not running. Please start Docker Desktop." -ForegroundColor Red
    exit 1
}

# 停止现有容器
Write-Host "`n[INFO] Stopping existing containers..." -ForegroundColor Blue
docker-compose -f docker-compose-fixed.yml down -v

# 启动数据库
Write-Host "`n[INFO] Starting MongoDB databases..." -ForegroundColor Blue
docker-compose -f docker-compose-fixed.yml up -d mongodb-source mongodb-target

# 等待数据库初始化
Write-Host "`n[INFO] Waiting for databases to initialize (45 seconds)..." -ForegroundColor Blue
Start-Sleep -Seconds 45

# 检查数据库状态
Write-Host "`n[INFO] Checking database status..." -ForegroundColor Blue
docker-compose -f docker-compose-fixed.yml ps

# 检查数据库连接
Write-Host "`n[INFO] Testing database connections..." -ForegroundColor Blue

# 测试源数据库
try {
    docker-compose -f docker-compose-fixed.yml exec mongodb-source mongosh --username admin --password password1 --authenticationDatabase admin --eval "db.adminCommand('ping')" | Out-Null
    Write-Host "[SUCCESS] Source database is accessible" -ForegroundColor Green
} catch {
    Write-Host "[ERROR] Source database is not accessible" -ForegroundColor Red
}

# 测试目标数据库
try {
    docker-compose -f docker-compose-fixed.yml exec mongodb-target mongosh --username admin --password password2 --authenticationDatabase admin --eval "db.adminCommand('ping')" | Out-Null
    Write-Host "[SUCCESS] Target database is accessible" -ForegroundColor Green
} catch {
    Write-Host "[ERROR] Target database is not accessible" -ForegroundColor Red
}

# 运行同步
Write-Host "`n[INFO] Running sync process..." -ForegroundColor Blue
docker-compose -f docker-compose-fixed.yml --profile sync run --rm mongosync /home/mongosync/scripts/fixed-sync.sh

# 显示结果
Write-Host "`n[SUCCESS] Setup completed!" -ForegroundColor Green
Write-Host "`n[INFO] Connection Information:" -ForegroundColor Blue
Write-Host "  Source Database: mongodb://admin:password1@localhost:20727/admin" -ForegroundColor Yellow
Write-Host "  Target Database: mongodb://admin:password2@localhost:20728/admin" -ForegroundColor Yellow

Write-Host "`n[INFO] Commands:" -ForegroundColor Blue
Write-Host "  View logs: docker-compose -f docker-compose-fixed.yml logs" -ForegroundColor Cyan
Write-Host "  Stop all: docker-compose -f docker-compose-fixed.yml down" -ForegroundColor Cyan
Write-Host "  Run diagnosis: .\diagnose-sync.bat" -ForegroundColor Cyan

Read-Host "`nPress Enter to continue" 